package com.uenpay.im.ui.old.activity;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.qiyunxin.android.http.listener.OnHttpRequestTextListener;
import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.net.HttpTextAsyncTask;
import com.qyx.android.aidl.IPushService;
import com.uenpay.im.IMApplication;
import com.uenpay.im.invokeitems.login.RegOrCancelDeviceNoInvokeItem;
import com.uenpay.im.service.PushService;

/**
 * service socket连接管理
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 *
 */
public class PushServiceConn {
	private Context mContext;
	/**
	 * service名称
	 */
	public static final String PUSH_SERVICE_NAME = IMApplication.getInstance()
			.getAppPackageName() + ".service.PushService";
	private Object sync = new Object();
	public IPushService pushService;
	public ServiceConnection mPushServiceConnection;

	private volatile static PushServiceConn instance;

	/**
	 * 获取连接对象实例
	 *
	 * @param context
	 * @return
	 */
	public static PushServiceConn getInstance(Context context) {
		if (context != null) {
			if (instance == null) {
				synchronized (PushServiceConn.class) {
					if (instance == null) {
						instance = new PushServiceConn(context);
					}
				}
			}
		}
		return instance;
	}

	public PushServiceConn(Context context) {
		mContext = context;
	}

	/**
	 * 开始连接
	 */
	public void startChatService() {
		synchronized (sync) {
			if (!isServiceRunning(PUSH_SERVICE_NAME) || pushService == null) {
				connPushService();
			}
		}
	}

	/**
	 * 判断程序是否运行
	 *
	 * @param className
	 * @return
	 *
	 */
	public boolean isServiceRunning(String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);

		for (RunningServiceInfo service : activityManager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (PUSH_SERVICE_NAME.equals(service.service.getClassName())) {
				isRunning = true;
			}
		}
		return isRunning;
	}

	/**
	 * 开始连接
	 */
	public void startConn() {
		IMApplication.setIsLogoutConfig(false);
		if (pushService == null) {
			connPushService();
			return;
		}

		try {
			if (pushService != null) {
				pushService.setLogout(false);
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 断开连接
	 */
	public void stopChatService() {
		IMApplication.setIsLogoutConfig(true);
		if (pushService == null) {
			connPushService();
			return;
		}
		try {
			if (pushService != null) {
				pushService.setLogout(true);
				cancelDeviceNo();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 注销设备号
	 */
	public void cancelDeviceNo() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				RegOrCancelDeviceNoInvokeItem item = new RegOrCancelDeviceNoInvokeItem(
						true);
				HttpRequestAsyncTaskQueue.getInstance().AddTask(
						new HttpTextAsyncTask(item)
								.SetRequestType(HttpRequestType.SERVER_ONLY),
						new OnHttpRequestTextListener() {

							@Override
							public void OnFail(boolean isCache, String reason) {
							}

							@Override
							public void OnProgress(long total_bytes,
									long downloaded_bytes) {
							}

							@Override
							public void OnSuccess(HttpInvokeItem item,
									boolean isCache, String cacheFilePath) {

							}
						});

			}
		}).start();
	}

	public void connPushService() {
		Intent intent = new Intent(mContext, PushService.class);
		mContext.startService(intent);
		if (mPushServiceConnection == null) {
			pushServiceConnection();
			mContext.bindService(intent, mPushServiceConnection,
					Context.BIND_AUTO_CREATE);
		}
	}

	private void pushServiceConnection() {
		mPushServiceConnection = new ServiceConnection() {
			@Override
			public void onServiceDisconnected(ComponentName name) {
				pushService = null;
				mContext.unbindService(mPushServiceConnection);
				mPushServiceConnection = null;
			}

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				pushService = IPushService.Stub.asInterface(service);
				try {
					pushService.regRecvMsgCallback(IMApplication.getCustId(),
							IMApplication.getAccessToken(), IMApplication.getAccessAuth());
					pushService.setLogout(IMApplication.getIsLogoutConfig());
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		};
	}
}
